package cn.lix.nio.demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {

    public static void main(String[] args) {
        //服务类
        ServerBootstrap bootStrap = new ServerBootstrap();
        //主要负责监听任务与分发
        EventLoopGroup boss = new NioEventLoopGroup(2);
        //主要负责任务的具体执行
        EventLoopGroup worker = new NioEventLoopGroup(10);

        bootStrap.group(boss, worker);

        bootStrap.channel(NioServerSocketChannel.class)// 指定NIO的模式
                .option(ChannelOption.SO_BACKLOG, 1024)// 设置tcp缓冲区
                .option(ChannelOption.SO_SNDBUF, 32 * 1024)// 设置发送缓冲大小
                .option(ChannelOption.SO_RCVBUF, 32 * 1024)// 这是接收缓冲大小
                .option(ChannelOption.SO_KEEPALIVE, true)// 保持连接
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new NettyServerHandler());
                    }
                });
        try {
            // 4 进行绑定
            ChannelFuture channelFuture = bootStrap.bind(8888).sync();
            // 5 等待关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }


}
